package com.test.daily.leetcode.y2022.m07.day0701.v07;

/**
 * @author Tom on 2022/7/3
 */
public class Solution {
    public int nextGreaterElement(int n) {
        char[] nums = Integer.toString(n).toCharArray();
        int i = nums.length - 2;
        while(i >= 0 && nums[i]>= nums[i+1]){
            i--;
        }
        if(i < 0){
            return -1;
        }
        int j = nums.length - 1;
        while(j >=0 && nums[j] <= nums[i]){
            j--;
        }
        swap(nums, i, j);
        reverse(nums, i+1);
        long ans = Long.parseLong(String.valueOf(nums));
        return ans > Integer.MAX_VALUE ? -1: (int)ans;
    }
    public void swap(char[] arr, int i, int j){
        char tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
    public void reverse(char[] arr, int start){
        int left = start, right = arr.length - 1;
        while(left < right){
            swap(arr, left, right);
            left--;
            right++;
        }
    }
}
